package xyz.zcq.zcqrpc;

import lombok.extern.slf4j.Slf4j;
import xyz.zcq.zcqrpc.config.RegistryConfig;
import xyz.zcq.zcqrpc.constant.RpcConstant;
import xyz.zcq.zcqrpc.config.RpcConfig;
import xyz.zcq.zcqrpc.registry.Registry;
import xyz.zcq.zcqrpc.registry.RegistryFactory;
import xyz.zcq.zcqrpc.utils.ConfigUtils;

/**
 * RPC框架应用
 */
@Slf4j
public class RpcApplication {

    /**
     * RPC框架配置
     */
    private static volatile RpcConfig rpcConfig;

    /**
     * 获取RPC框架配置
     *
     * @return RPC框架配置
     */
    public static RpcConfig getRpcConfig() {
        if (rpcConfig == null) {
            synchronized (RpcApplication.class) {
                if (rpcConfig == null) {
                    try {
                        rpcConfig = ConfigUtils.loadConfig(RpcConfig.class, RpcConstant.DEFAULT_CONFIG_PREFIX);
                    } catch (Exception e) {
                        rpcConfig = new RpcConfig();
                    }

                    RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
                    Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
                    registry.init(registryConfig);
                    log.info("registry init, config = {}", registryConfig);
                    Runtime.getRuntime().addShutdownHook(new Thread(registry::destroy));
                }
            }
        }

        return rpcConfig;
    }

}
